package middleware

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"server/internal/consts"
	"server/internal/errors"
	"server/internal/service"
	"server/internal/tool"
)

func LessonAuthHandler(r *ghttp.Request) {
	ctx := r.GetCtx()
	// 权限URI
	route := tool.BuildAuthRoute(r.Method, r.Request.URL.Path)

	//判断是否是不需要验证登录的路由地址
	if checkExceptLoginRoute(ctx, route, "router.lesson.exceptLogin") {
		r.Middleware.Next()
		return
	}

	userID, err := service.LessonUser().ParseLoginUserID(r.GetCtx())
	if userID == 0 || err != nil {
		Response(r, errors.CodeNoLogin, "未登录", g.Array{})
		r.ExitAll()
		return
	}

	//将用户ID写入上下文
	r.SetCtxVar(consts.CtxLessonUserID, userID)

	// 验证通过
	r.Middleware.Next()
	return
}
